require "state_machine"

class PaperRegisterRepo < Sequel::Model(:paper_register)
  plugin :validation_helpers
  many_to_one :paper_type, class: "PaperTypeRepo"
  
  state_machine :state, :initial => :normal do
    event :expire do
      transition [:normal] => :expired
    end

    event :hangup do
      transition [:normal, :expired] => :failure
    end

    event :restore do
      transition [:failure, :expired] => :normal
    end
  end



  def validate
    super
    validates_unique   [:employee_id, :paper_type_id]
    validates_presence [:employee_id, :paper_type_id, :paper_no, :due_date]
  end
  


  def perfect
    employee = PositionRepo[employee_id]
    {
      id: id,
      employee: {id: employee.id, name: employee.name},
      paper_type:  {id: paper_type.id, name: paper_type.name},
      paper_no: paper_no,
      due_date: due_date,
      descr: descr,
      state: state
    }
  end


  def check_expire
    if (due_date < Date.today)
      self.expire
    else
      self.restore
    end
  end

    

  def self.group(e_id)
    result = PaperRegisterRepo.where(employee_id: e_id)
    employee = EmployeeRepo[e_id]

    {
      employee: {id: employee.id, name: employee.name},
      papers: result.map do |e|
        e.values.merge({paper_type: {id: e.paper_type.id, name: e.paper_type.name}}).tap {|h| h.delete(:employee_id)}.tap {|h| h.delete(:paper_type_id)}
      end
    }
  end
end
